package cn.jiedh.app.meiweidk.register;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.location.LocationManager;
import android.support.design.widget.CoordinatorLayout;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.umeng.analytics.MobclickAgent;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jiedh.app.meiweidk.MainActivity;
import cn.jiedh.app.meiweidk.R;
import cn.jiedh.app.meiweidk.Utils.UI.MyTBView;
import cn.jiedh.app.meiweidk.Utils.tool.ActivityUtil;
import cn.jiedh.app.meiweidk.Utils.tool.BitmapUtil;
import cn.jiedh.app.meiweidk.Utils.tool.LocationUtil;
import cn.jiedh.app.meiweidk.Utils.tool.SPUtils;
import cn.jiedh.app.meiweidk.Utils.tool.StringUtil;
import cn.jiedh.app.meiweidk.Utils.tool.T;
import cn.jiedh.app.meiweidk.Utils.tool.UrlUtils;
import cn.jiedh.app.meiweidk.Utils.tool.ValidateUtils;
import cn.jiedh.app.meiweidk.base.BaseActivity;
import cn.jiedh.app.meiweidk.buried.BuriedBean;
import cn.jiedh.app.meiweidk.entity.ImageCodeBean;
import cn.jiedh.app.meiweidk.entity.LoginAndRegisterBean;
import cn.jiedh.app.meiweidk.network.ResponseSuccess;
import cn.jiedh.app.meiweidk.response.BaseResponse;
import cn.jpush.android.api.JPushInterface;

/**
 * @name：注册
 * @author： 司马林
 * @phone： 18423134135
 * @createTime： 2017/10/19
 * @modifyTime： 2017/10/19
 */

public class RegisterActivity extends BaseActivity {
    @BindView(R.id.bar_tv_title)
    TextView title;
    @BindView(R.id.phone)
    EditText phoneEdt;
    @BindView(R.id.psw_edt)
    EditText pswEdt;
    @BindView(R.id.verification_edt)
    EditText verificationEdt;
    @BindView(R.id.verification_btn)
    MyTBView verificationBtn;
    @BindView(R.id.coordinator)
    CoordinatorLayout coordinatorLayout;
    @BindView(R.id.register_btn)
    Button registerBtn;
    @BindView(R.id.image_code_edt)
    EditText imageCodeEdt;
    @BindView(R.id.image_code_img)
    ImageView imageCodeImg;
    @BindView(R.id.image_code_layout)
    LinearLayout imageCodeLayout;
    @BindView(R.id.is_read_user_agreement)
    CheckBox isReadUserAgreementCB;

    private String img;
    private String imgKey;

    private List<BuriedBean> buriedList;


    @Override
    protected int getLayoutView() {
        return R.layout.activity_register;
    }

    @Override
    protected void initView(View view) {
        title.setText("注册");
    }

    @Override
    protected void initData() {
        verificationEdt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {

                    InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);

                    String phone = phoneEdt.getText().toString();
                    String psw = pswEdt.getText().toString();
                    String verificationCode = verificationEdt.getText().toString();
                    String errorStr = ValidateUtils.isRegister(phone, false, null, verificationCode, psw);
                    boolean isReadUserAgreement = isReadUserAgreementCB.isChecked();
                    if (TextUtils.isEmpty(errorStr) && !isReadUserAgreement) {
                        errorStr = "请同意用户协议";
                    }
                    if ("".equals(errorStr) && isReadUserAgreement) {
                        register(phone, psw, verificationCode);
                    } else {
                        T.showShortCenterToast(errorStr);
                    }
                }
                return false;
            }
        });
//        getImageCode();
    }

    @OnClick({R.id.bar_img_back, R.id.user_agreement_tv, R.id.register_btn, R.id.verification_btn, R.id.image_code_img})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bar_img_back:
                break;
            case R.id.user_agreement_tv:
                Intent intent = new Intent(this, UserAgreementActivity.class);
                startActivityForResult(intent, 1);
                break;
            case R.id.verification_btn:
                MobclickAgent.onEvent(this,"regist_getCode");
                SPUtils.saveBuried("registry","0","注册-获取验证码","true",
                        "注册","","","");
                InputMethodManager imm = (InputMethodManager) verificationBtn.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(verificationBtn.getWindowToken(), 0);

//                if (StringUtil.isMobileNO(phoneEdt.getText().toString())) {
                    getSMSVerification(phoneEdt.getText().toString());
//                } else {
//                    T.showShortCenterToast("请输入正确的手机号");
//                }
                break;
            case R.id.register_btn:
                MobclickAgent.onEvent(this, "register");
                MobclickAgent.onEvent(this, "regist_registRightNow");
                InputMethodManager imm1 = (InputMethodManager) registerBtn.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm1.hideSoftInputFromWindow(registerBtn.getWindowToken(), 0);

                String phone = phoneEdt.getText().toString();
                String psw = pswEdt.getText().toString();
                String verificationCode = verificationEdt.getText().toString();
                String errorStr = ValidateUtils.isRegister(phone, false, null, verificationCode, psw);
                boolean isReadUserAgreement = isReadUserAgreementCB.isChecked();
                if (TextUtils.isEmpty(errorStr) && !isReadUserAgreement) {
                    errorStr = "请同意用户协议";
                }
                if ("".equals(errorStr) && isReadUserAgreement) {
                    SPUtils.saveBuried("registry","0","注册-立即注册","",
                            "注册","","","");
                    register(phone, psw, verificationCode);
                } else {
                    T.showShortCenterToast(errorStr);
                }
                break;
            case R.id.image_code_img:
//                getImageCode();
                break;
            default:
                break;
        }
    }

    private void register(String phone, String psw, String verificationCode) {
        showLoadingDialog();
        Map<String, Object> map = new HashMap<>();
        map.put("phone", phone);
        map.put("code", verificationCode);
        map.put("password", psw);
//        LocationManager locationManager = (LocationManager) this.getApplication().getSystemService(Context.LOCATION_SERVICE);
//        Double[] doubles = LocationUtil.getGpsLocation(this.getApplicationContext(), locationManager);
        Double[] doubles = LocationUtil.location;

        if (doubles != null) {
            Double lat = doubles[0];
            Double lng = doubles[1];
            map.put("longitude", lng);
            map.put("latitude", lat);
        }

        request(this, UrlUtils.REGISTER, map, true, new ResponseSuccess<LoginAndRegisterBean>() {
            @Override
            public void onRequestSucceed(BaseResponse<LoginAndRegisterBean> response) {
                dismissLoadingDialog();
                T.showShort(response.getMessage());
                if (0 == response.getCode()) {
                    login(phone, psw);
                }
            }
        });
    }

    private void getSMSVerification(String phone) {
        verificationBtn.start();
        showLoadingDialog();
        Map<String, Object> map = new HashMap<>();
        map.put("phone", phone);
        map.put("imgKey", imgKey);
        map.put("imgCode", imageCodeEdt.getText().toString());
        request(this, UrlUtils.REGISTERSMSCODE, map, false, response -> {
            dismissLoadingDialog();
            if (0 != response.getCode()) {
                T.showShort(response.getMessage());
            }
        });
    }

//    private void getImageCode() {
//        Map<String, Object> map = new HashMap<>();
//        showLoadingDialog();
//        request(this, UrlUtils.IMAGECODE, map, false, new ResponseSuccess<ImageCodeBean>() {
//            @Override
//            public void onRequestSucceed(BaseResponse<ImageCodeBean> response) {
//                dismissLoadingDialog();
//                if (0 == response.getCode()) {
//                    imageCodeLayout.setVisibility(View.GONE);
//                } else if (1 == response.getCode()) {
//                    T.showShort(response.getMessage());
//                    imageCodeLayout.setVisibility(View.GONE);
//                } else if (3 == response.getCode()) {
//                    img = response.getData().getImg();
//                    imgKey = response.getData().getImgKey();
//
//                    Bitmap b = BitmapUtil.stringtoBitmap(img);
//                    imgKey = response.getData().getImgKey();
//                    imageCodeImg.setImageBitmap(b);
//                    imageCodeLayout.setVisibility(View.VISIBLE);
//                }
//            }
//        });
//    }

    private void login(String phone, String psw) {
        showLoadingDialog();
        Map<String, Object> map = new HashMap<>();
        map.put("phone", phone);
        map.put("password", psw);
        showLoadingDialog();
        request(this, UrlUtils.PSWLOGIN, map, true, new ResponseSuccess<LoginAndRegisterBean>() {
            @Override
            public void onRequestSucceed(BaseResponse<LoginAndRegisterBean> response) {
                dismissLoadingDialog();
                if (0 == response.getCode()) {
                    SPUtils.saveUser(phone, response.getData().getToken());
                    JPushInterface.setAlias(activity, SPUtils.getPhone(), null);
                    ActivityUtil.next(RegisterActivity.this, MainActivity.class);
                } else {
                    T.showShort(response.getMessage());
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == UserAgreementActivity.REGISTER_RESULT_CODE) {
            isReadUserAgreementCB.setChecked(true);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
        verificationBtn.stop();
    }
}
